home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 1998 November / IRIX 6.5.2 Base Documentation November 1998.img / usr / share / catman / u_man / cat1 / perlxstut.z / perlxstut
Text File  |  1998-10-30  |  38KB  |  1,057 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlXStut - Tutorial for XSUBs
  10.  
  11. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.      This tutorial will educate the reader on the steps involved in creating a
  13.      Perl extension.  The reader is assumed to have access to the _p_e_r_l_g_u_t_s
  14.      manpage and the _p_e_r_l_x_s manpage.
  15.  
  16.      This tutorial starts with very simple examples and becomes more complex,
  17.      with each new example adding new features.  Certain concepts may not be
  18.      completely explained until later in the tutorial to ease the reader
  19.      slowly into building extensions.
  20.  
  21.      VVVVEEEERRRRSSSSIIIIOOOONNNN CCCCAAAAVVVVEEEEAAAATTTT
  22.  
  23.      This tutorial tries hard to keep up with the latest development versions
  24.      of Perl.  This often means that it is sometimes in advance of the latest
  25.      released version of Perl, and that certain features described here might
  26.      not work on earlier versions.  This section will keep track of when
  27.      various features were added to Perl 5.
  28.  
  29.      +o   In versions of Perl 5.002 prior to the gamma version, the test script
  30.          in Example 1 will not function properly.  You need to change the "use
  31.          lib" line to read:
  32.  
  33.                  use lib './blib';
  34.  
  35.  
  36.      +o   In versions of Perl 5.002 prior to version beta 3, the line in the
  37.          .xs file about "PROTOTYPES: DISABLE" will cause a compiler error.
  38.          Simply remove that line from the file.
  39.  
  40.      +o   In versions of Perl 5.002 prior to version 5.002b1h, the test.pl file
  41.          was not automatically created by h2xs.  This means that you cannot
  42.          say "make test" to run the test script.  You will need to add the
  43.          following line before the "use extension" statement:
  44.  
  45.                  use lib './blib';
  46.  
  47.  
  48.      +o   In versions 5.000 and 5.001, instead of using the above line, you
  49.          will need to use the following line:
  50.  
  51.                  BEGIN { unshift(@INC, "./blib") }
  52.  
  53.  
  54.      +o   This document assumes that the executable named "perl" is Perl
  55.          version 5.  Some systems may have installed Perl version 5 as
  56.          "perl5".
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  71.  
  72.  
  73.  
  74.      DDDDYYYYNNNNAAAAMMMMIIIICCCC VVVVEEEERRRRSSSSUUUUSSSS SSSSTTTTAAAATTTTIIIICCCC
  75.  
  76.      It is commonly thought that if a system does not have the capability to
  77.      load a library dynamically, you cannot build XSUBs.  This is incorrect.
  78.      You _c_a_n build them, but you must link the XSUB's subroutines with the
  79.      rest of Perl, creating a new executable.  This situation is similar to
  80.      Perl 4.
  81.  
  82.      This tutorial can still be used on such a system.  The XSUB build
  83.      mechanism will check the system and build a dynamically-loadable library
  84.      if possible, or else a static library and then, optionally, a new
  85.      statically-linked executable with that static library linked in.
  86.  
  87.      Should you wish to build a statically-linked executable on a system which
  88.      can dynamically load libraries, you may, in all the following examples,
  89.      where the command "make" with no arguments is executed, run the command
  90.      "make perl" instead.
  91.  
  92.      If you have generated such a statically-linked executable by choice, then
  93.      instead of saying "make test", you should say "make test_static".  On
  94.      systems that cannot build dynamically-loadable libraries at all, simply
  95.      saying "make test" is sufficient.
  96.  
  97.      EEEEXXXXAAAAMMMMPPPPLLLLEEEE 1111
  98.  
  99.      Our first extension will be very simple.  When we call the routine in the
  100.      extension, it will print out a well-known message and return.
  101.  
  102.      Run h2xs -A -n Mytest.  This creates a directory named Mytest, possibly
  103.      under ext/ if that directory exists in the current working directory.
  104.      Several files will be created in the Mytest dir, including MANIFEST,
  105.      Makefile.PL, Mytest.pm, Mytest.xs, test.pl, and Changes.
  106.  
  107.      The MANIFEST file contains the names of all the files created.
  108.  
  109.      The file Makefile.PL should look something like this:
  110.  
  111.              use ExtUtils::MakeMaker;
  112.              # See lib/ExtUtils/MakeMaker.pm for details of how to influence
  113.              # the contents of the Makefile that is written.
  114.              WriteMakefile(
  115.                  'NAME'      => 'Mytest',
  116.                  'VERSION_FROM' => 'Mytest.pm', # finds $VERSION
  117.                  'LIBS'      => [''],   # e.g., '-lm'
  118.                  'DEFINE'    => '',     # e.g., '-DHAVE_SOMETHING'
  119.                  'INC'       => '',     # e.g., '-I/usr/include/other'
  120.              );
  121.  
  122.      The file Mytest.pm should start with something like this:
  123.  
  124.  
  125.  
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  137.  
  138.  
  139.  
  140.              package Mytest;
  141.  
  142.              require Exporter;
  143.              require DynaLoader;
  144.  
  145.              @ISA = qw(Exporter DynaLoader);
  146.              # Items to export into callers namespace by default. Note: do not export
  147.              # names by default without a very good reason. Use EXPORT_OK instead.
  148.              # Do not simply export all your public functions/methods/constants.
  149.              @EXPORT = qw(
  150.  
  151.              );
  152.              $VERSION = '0.01';
  153.  
  154.              bootstrap Mytest $VERSION;
  155.  
  156.              # Preloaded methods go here.
  157.  
  158.              # Autoload methods go after __END__, and are processed by the autosplit program.
  159.  
  160.              1;
  161.              __END__
  162.              # Below is the stub of documentation for your module. You better edit it!
  163.  
  164.      And the Mytest.xs file should look something like this:
  165.  
  166.              #ifdef __cplusplus
  167.              extern "C" {
  168.              #endif
  169.              #include "EXTERN.h"
  170.              #include "perl.h"
  171.              #include "XSUB.h"
  172.              #ifdef __cplusplus
  173.              }
  174.              #endif
  175.  
  176.              PROTOTYPES: DISABLE
  177.  
  178.              MODULE = Mytest         PACKAGE = Mytest
  179.  
  180.      Let's edit the .xs file by adding this to the end of the file:
  181.  
  182.              void
  183.              hello()
  184.                      CODE:
  185.                      printf("Hello, world!\n");
  186.  
  187.      Now we'll run "perl Makefile.PL".  This will create a real Makefile,
  188.      which make needs.  Its output looks something like:
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  203.  
  204.  
  205.  
  206.              % perl Makefile.PL
  207.              Checking if your kit is complete...
  208.              Looks good
  209.              Writing Makefile for Mytest
  210.              %
  211.  
  212.      Now, running make will produce output that looks something like this
  213.      (some long lines shortened for clarity):
  214.  
  215.              % make
  216.              umask 0 && cp Mytest.pm ./blib/Mytest.pm
  217.              perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c
  218.              cc -c Mytest.c
  219.              Running Mkbootstrap for Mytest ()
  220.              chmod 644 Mytest.bs
  221.              LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl -b Mytest.o
  222.              chmod 755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl
  223.              cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
  224.              chmod 644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
  225.  
  226.      Now, although there is already a test.pl template ready for us, for this
  227.      example only, we'll create a special test script.  Create a file called
  228.      hello that looks like this:
  229.  
  230.              #! /opt/perl5/bin/perl
  231.  
  232.              use ExtUtils::testlib;
  233.  
  234.              use Mytest;
  235.  
  236.              Mytest::hello();
  237.  
  238.      Now we run the script and we should see the following output:
  239.  
  240.              % perl hello
  241.              Hello, world!
  242.              %
  243.  
  244.  
  245.      EEEEXXXXAAAAMMMMPPPPLLLLEEEE 2222
  246.  
  247.      Now let's add to our extension a subroutine that will take a single
  248.      argument and return 1 if the argument is even, 0 if the argument is odd.
  249.  
  250.      Add the following to the end of Mytest.xs:
  251.  
  252.  
  253.  
  254.  
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  269.  
  270.  
  271.  
  272.              int
  273.              is_even(input)
  274.                      int     input
  275.                      CODE:
  276.                      RETVAL = (input % 2 == 0);
  277.                      OUTPUT:
  278.                      RETVAL
  279.  
  280.      There does not need to be white space at the start of the "int input"
  281.      line, but it is useful for improving readability.  The semi-colon at the
  282.      end of that line is also optional.
  283.  
  284.      Any white space may be between the "int" and "input".  It is also okay
  285.      for the four lines starting at the "CODE:" line to not be indented.
  286.      However, for readability purposes, it is suggested that you indent them 8
  287.      spaces (or one normal tab stop).
  288.  
  289.      Now rerun make to rebuild our new shared library.
  290.  
  291.      Now perform the same steps as before, generating a Makefile from the
  292.      Makefile.PL file, and running make.
  293.  
  294.      To test that our extension works, we now need to look at the file
  295.      test.pl.  This file is set up to imitate the same kind of testing
  296.      structure that Perl itself has.  Within the test script, you perform a
  297.      number of tests to confirm the behavior of the extension, printing "ok"
  298.      when the test is correct, "not ok" when it is not.  Change the print
  299.      statement in the BEGIN block to print "1..4", and add the following code
  300.      to the end of the file:
  301.  
  302.              print &Mytest::is_even(0) == 1 ? "ok 2" : "not ok 2", "\n";
  303.              print &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3", "\n";
  304.              print &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4", "\n";
  305.  
  306.      We will be calling the test script through the command "make test".  You
  307.      should see output that looks something like this:
  308.  
  309.              % make test
  310.              PERL_DL_NONLAZY=1 /opt/perl5.002b2/bin/perl (lots of -I arguments) test.pl
  311.              1..4
  312.              ok 1
  313.              ok 2
  314.              ok 3
  315.              ok 4
  316.              %
  317.  
  318.  
  319.      WWWWHHHHAAAATTTT HHHHAAAASSSS GGGGOOOONNNNEEEE OOOONNNN????
  320.  
  321.      The program h2xs is the starting point for creating extensions.  In later
  322.      examples we'll see how we can use h2xs to read header files and generate
  323.      templates to connect to C routines.
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  335.  
  336.  
  337.  
  338.      h2xs creates a number of files in the extension directory.  The file
  339.      Makefile.PL is a perl script which will generate a true Makefile to build
  340.      the extension.  We'll take a closer look at it later.
  341.  
  342.      The files <extension>.pm and <extension>.xs contain the meat of the
  343.      extension.  The .xs file holds the C routines that make up the extension.
  344.      The .pm file contains routines that tell Perl how to load your extension.
  345.  
  346.      Generating and invoking the Makefile created a directory blib (which
  347.      stands for "build library") in the current working directory.  This
  348.      directory will contain the shared library that we will build.  Once we
  349.      have tested it, we can install it into its final location.
  350.  
  351.      Invoking the test script via "make test" did something very important.
  352.      It invoked perl with all those -I arguments so that it could find the
  353.      various files that are part of the extension.
  354.  
  355.      It is _v_e_r_y important that while you are still testing extensions that you
  356.      use "make test".  If you try to run the test script all by itself, you
  357.      will get a fatal error.
  358.  
  359.      Another reason it is important to use "make test" to run your test script
  360.      is that if you are testing an upgrade to an already-existing version,
  361.      using "make test" insures that you use your new extension, not the
  362.      already-existing version.
  363.  
  364.      When Perl sees a use extension;, it searches for a file with the same
  365.      name as the use'd extension that has a .pm suffix.  If that file cannot
  366.      be found, Perl dies with a fatal error.  The default search path is
  367.      contained in the @INC array.
  368.  
  369.      In our case, Mytest.pm tells perl that it will need the Exporter and
  370.      Dynamic Loader extensions.  It then sets the @ISA and @EXPORT arrays and
  371.      the $VERSION scalar; finally it tells perl to bootstrap the module.  Perl
  372.      will call its dynamic loader routine (if there is one) and load the
  373.      shared library.
  374.  
  375.      The two arrays that are set in the .pm file are very important.  The @ISA
  376.      array contains a list of other packages in which to search for methods
  377.      (or subroutines) that do not exist in the current package.  The @EXPORT
  378.      array tells Perl which of the extension's routines should be placed into
  379.      the calling package's namespace.
  380.  
  381.      It's important to select what to export carefully.  Do NOT export method
  382.      names and do NOT export anything else _b_y _d_e_f_a_u_l_t without a good reason.
  383.  
  384.      As a general rule, if the module is trying to be object-oriented then
  385.      don't export anything.  If it's just a collection of functions then you
  386.      can export any of the functions via another array, called @EXPORT_OK.
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  401.  
  402.  
  403.  
  404.      See the _p_e_r_l_m_o_d manpage for more information.
  405.  
  406.      The $VERSION variable is used to ensure that the .pm file and the shared
  407.      library are "in sync" with each other.  Any time you make changes to the
  408.      .pm or .xs files, you should increment the value of this variable.
  409.  
  410.      WWWWRRRRIIIITTTTIIIINNNNGGGG GGGGOOOOOOOODDDD TTTTEEEESSSSTTTT SSSSCCCCRRRRIIIIPPPPTTTTSSSS
  411.  
  412.      The importance of writing good test scripts cannot be overemphasized.
  413.      You should closely follow the "ok/not ok" style that Perl itself uses, so
  414.      that it is very easy and unambiguous to determine the outcome of each
  415.      test case.  When you find and fix a bug, make sure you add a test case
  416.      for it.
  417.  
  418.      By running "make test", you ensure that your test.pl script runs and uses
  419.      the correct version of your extension.  If you have many test cases, you
  420.      might want to copy Perl's test style.  Create a directory named "t", and
  421.      ensure all your test files end with the suffix ".t".  The Makefile will
  422.      properly run all these test files.
  423.  
  424.      EEEEXXXXAAAAMMMMPPPPLLLLEEEE 3333
  425.  
  426.      Our third extension will take one argument as its input, round off that
  427.      value, and set the _a_r_g_u_m_e_n_t to the rounded value.
  428.  
  429.      Add the following to the end of Mytest.xs:
  430.  
  431.              void
  432.              round(arg)
  433.                      double  arg
  434.                      CODE:
  435.                      if (arg > 0.0) {
  436.                              arg = floor(arg + 0.5);
  437.                      } else if (arg < 0.0) {
  438.                              arg = ceil(arg - 0.5);
  439.                      } else {
  440.                              arg = 0.0;
  441.                      }
  442.                      OUTPUT:
  443.                      arg
  444.  
  445.      Edit the Makefile.PL file so that the corresponding line looks like this:
  446.  
  447.              'LIBS'      => ['-lm'],   # e.g., '-lm'
  448.  
  449.      Generate the Makefile and run make.  Change the BEGIN block to print out
  450.      "1..9" and add the following to test.pl:
  451.  
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  467.  
  468.  
  469.  
  470.              $i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok 5" : "not ok 5", "\n";
  471.              $i = -1.1; &Mytest::round($i); print $i == -1.0 ? "ok 6" : "not ok 6", "\n";
  472.              $i = 0.0; &Mytest::round($i); print $i == 0.0 ? "ok 7" : "not ok 7", "\n";
  473.              $i = 0.5; &Mytest::round($i); print $i == 1.0 ? "ok 8" : "not ok 8", "\n";
  474.              $i = 1.2; &Mytest::round($i); print $i == 1.0 ? "ok 9" : "not ok 9", "\n";
  475.  
  476.      Running "make test" should now print out that all nine tests are okay.
  477.  
  478.      You might be wondering if you can round a constant.  To see what happens,
  479.      add the following line to test.pl temporarily:
  480.  
  481.              &Mytest::round(3);
  482.  
  483.      Run "make test" and notice that Perl dies with a fatal error.  Perl won't
  484.      let you change the value of constants!
  485.  
  486.      WWWWHHHHAAAATTTT''''SSSS NNNNEEEEWWWW HHHHEEEERRRREEEE????
  487.  
  488.      Two things are new here.  First, we've made some changes to Makefile.PL.
  489.      In this case, we've specified an extra library to link in, the math
  490.      library libm.  We'll talk later about how to write XSUBs that can call
  491.      every routine in a library.
  492.  
  493.      Second, the value of the function is being passed back not as the
  494.      function's return value, but through the same variable that was passed
  495.      into the function.
  496.  
  497.      IIIINNNNPPPPUUUUTTTT AAAANNNNDDDD OOOOUUUUTTTTPPPPUUUUTTTT PPPPAAAARRRRAAAAMMMMEEEETTTTEEEERRRRSSSS
  498.  
  499.      You specify the parameters that will be passed into the XSUB just after
  500.      you declare the function return value and name.  Each parameter line
  501.      starts with optional white space, and may have an optional terminating
  502.      semicolon.
  503.  
  504.      The list of output parameters occurs after the OUTPUT: directive.  The
  505.      use of RETVAL tells Perl that you wish to send this value back as the
  506.      return value of the XSUB function.  In Example 3, the value we wanted
  507.      returned was contained in the same variable we passed in, so we listed it
  508.      (and not RETVAL) in the OUTPUT: section.
  509.  
  510.      TTTTHHHHEEEE XXXXSSSSUUUUBBBBPPPPPPPP CCCCOOOOMMMMPPPPIIIILLLLEEEERRRR
  511.  
  512.      The compiler xsubpp takes the XS code in the .xs file and converts it
  513.      into C code, placing it in a file whose suffix is .c.  The C code created
  514.      makes heavy use of the C functions within Perl.
  515.  
  516.      TTTTHHHHEEEE TTTTYYYYPPPPEEEEMMMMAAAAPPPP FFFFIIIILLLLEEEE
  517.  
  518.      The xsubpp compiler uses rules to convert from Perl's data types (scalar,
  519.      array, etc.) to C's data types (int, char *, etc.).  These rules are
  520.      stored in the typemap file ($PERLLIB/ExtUtils/typemap).  This file is
  521.      split into three parts.
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  533.  
  534.  
  535.  
  536.      The first part attempts to map various C data types to a coded flag,
  537.      which has some correspondence with the various Perl types.  The second
  538.      part contains C code which xsubpp uses for input parameters.  The third
  539.      part contains C code which xsubpp uses for output parameters.  We'll talk
  540.      more about the C code later.
  541.  
  542.      Let's now take a look at a portion of the .c file created for our
  543.      extension.
  544.  
  545.              XS(XS_Mytest_round)
  546.              {
  547.                  dXSARGS;
  548.                  if (items != 1)
  549.                      croak("Usage: Mytest::round(arg)");
  550.                  {
  551.                      double  arg = (double)SvNV(ST(0));      /* XXXXX */
  552.                      if (arg > 0.0) {
  553.                              arg = floor(arg + 0.5);
  554.                      } else if (arg < 0.0) {
  555.                              arg = ceil(arg - 0.5);
  556.                      } else {
  557.                              arg = 0.0;
  558.                      }
  559.                      sv_setnv(ST(0), (double)arg);   /* XXXXX */
  560.                  }
  561.                  XSRETURN(1);
  562.              }
  563.  
  564.      Notice the two lines marked with "XXXXX".  If you check the first section
  565.      of the typemap file, you'll see that doubles are of type T_DOUBLE.  In
  566.      the INPUT section, an argument that is T_DOUBLE is assigned to the
  567.      variable arg by calling the routine SvNV on something, then casting it to
  568.      double, then assigned to the variable arg.  Similarly, in the OUTPUT
  569.      section, once arg has its final value, it is passed to the sv_setnv
  570.      function to be passed back to the calling subroutine.  These two
  571.      functions are explained in the _p_e_r_l_g_u_t_s manpage; we'll talk more later
  572.      about what that "_S_T(0)" means in the section on the argument stack.
  573.  
  574.      WWWWAAAARRRRNNNNIIIINNNNGGGG
  575.  
  576.      In general, it's not a good idea to write extensions that modify their
  577.      input parameters, as in Example 3.  However, to accommodate better
  578.      calling pre-existing C routines, which often do modify their input
  579.      parameters, this behavior is tolerated.  The next example will show how
  580.      to do this.
  581.  
  582.      EEEEXXXXAAAAMMMMPPPPLLLLEEEE 4444
  583.  
  584.      In this example, we'll now begin to write XSUBs that will interact with
  585.      predefined C libraries.  To begin with, we will build a small library of
  586.      our own, then let h2xs write our .pm and .xs files for us.
  587.  
  588.  
  589.  
  590.  
  591.                                                                         PPPPaaaaggggeeee 9999
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  599.  
  600.  
  601.  
  602.      Create a new directory called Mytest2 at the same level as the directory
  603.      Mytest.  In the Mytest2 directory, create another directory called mylib,
  604.      and cd into that directory.
  605.  
  606.      Here we'll create some files that will generate a test library.  These
  607.      will include a C source file and a header file.  We'll also create a
  608.      Makefile.PL in this directory.  Then we'll make sure that running make at
  609.      the Mytest2 level will automatically run this Makefile.PL file and the
  610.      resulting Makefile.
  611.  
  612.      In the testlib directory, create a file mylib.h that looks like this:
  613.  
  614.              #define TESTVAL 4
  615.  
  616.              extern double   foo(int, long, const char*);
  617.  
  618.      Also create a file mylib.c that looks like this:
  619.  
  620.              #include <stdlib.h>
  621.              #include "./mylib.h"
  622.  
  623.              double
  624.              foo(a, b, c)
  625.              int             a;
  626.              long            b;
  627.              const char *    c;
  628.              {
  629.                      return (a + b + atof(c) + TESTVAL);
  630.              }
  631.  
  632.      And finally create a file Makefile.PL that looks like this:
  633.  
  634.              use ExtUtils::MakeMaker;
  635.              $Verbose = 1;
  636.              WriteMakefile(
  637.                  NAME      => 'Mytest2::mylib',
  638.                  SKIP      => [qw(all static static_lib dynamic dynamic_lib)],
  639.                  clean     => {'FILES' => 'libmylib$(LIB_EXT)'},
  640.              );
  641.  
  642.              sub MY::top_targets {
  643.                      '
  644.              all :: static
  645.  
  646.              static ::       libmylib$(LIB_EXT)
  647.  
  648.              libmylib$(LIB_EXT): $(O_FILES)
  649.                      $(AR) cr libmylib$(LIB_EXT) $(O_FILES)
  650.                      $(RANLIB) libmylib$(LIB_EXT)
  651.  
  652.              ';
  653.              }
  654.  
  655.  
  656.  
  657.                                                                        PPPPaaaaggggeeee 11110000
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  665.  
  666.  
  667.  
  668.      We will now create the main top-level Mytest2 files.  Change to the
  669.      directory above Mytest2 and run the following command:
  670.  
  671.              % h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h
  672.  
  673.      This will print out a warning about overwriting Mytest2, but that's okay.
  674.      Our files are stored in Mytest2/mylib, and will be untouched.
  675.  
  676.      The normal Makefile.PL that h2xs generates doesn't know about the mylib
  677.      directory.  We need to tell it that there is a subdirectory and that we
  678.      will be generating a library in it.  Let's add the following key-value
  679.      pair to the WriteMakefile call:
  680.  
  681.              'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)',
  682.  
  683.      and a new replacement subroutine too:
  684.  
  685.              sub MY::postamble {
  686.              '
  687.              $(MYEXTLIB): mylib/Makefile
  688.                      cd mylib && $(MAKE) $(PASTHRU)
  689.              ';
  690.              }
  691.  
  692.      (Note: Most makes will require that there be a tab character that indents
  693.      the line cd mylib && $(MAKE) $(PASTHRU), similarly for the Makefile in
  694.      the subdirectory.)
  695.  
  696.      Let's also fix the MANIFEST file so that it accurately reflects the
  697.      contents of our extension.  The single line that says "mylib" should be
  698.      replaced by the following three lines:
  699.  
  700.              mylib/Makefile.PL
  701.              mylib/mylib.c
  702.              mylib/mylib.h
  703.  
  704.      To keep our namespace nice and unpolluted, edit the .pm file and change
  705.      the lines setting @EXPORT to @EXPORT_OK (there are two: one in the line
  706.      beginning "use vars" and one setting the array itself).  Finally, in the
  707.      .xs file, edit the #include line to read:
  708.  
  709.              #include "mylib/mylib.h"
  710.  
  711.      And also add the following function definition to the end of the .xs
  712.      file:
  713.  
  714.  
  715.  
  716.  
  717.  
  718.  
  719.  
  720.  
  721.  
  722.  
  723.                                                                        PPPPaaaaggggeeee 11111111
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  731.  
  732.  
  733.  
  734.              double
  735.              foo(a,b,c)
  736.                      int             a
  737.                      long            b
  738.                      const char *    c
  739.                      OUTPUT:
  740.                      RETVAL
  741.  
  742.      Now we also need to create a typemap file because the default Perl
  743.      doesn't currently support the const char * type.  Create a file called
  744.      typemap and place the following in it:
  745.  
  746.              const char *    T_PV
  747.  
  748.      Now run perl on the top-level Makefile.PL.  Notice that it also created a
  749.      Makefile in the mylib directory.  Run make and see that it does cd into
  750.      the mylib directory and run make in there as well.
  751.  
  752.      Now edit the test.pl script and change the BEGIN block to print "1..4",
  753.      and add the following lines to the end of the script:
  754.  
  755.              print &Mytest2::foo(1, 2, "Hello, world!") == 7 ? "ok 2\n" : "not ok 2\n";
  756.              print &Mytest2::foo(1, 2, "0.0") == 7 ? "ok 3\n" : "not ok 3\n";
  757.              print abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 ? "ok 4\n" : "not ok 4\n";
  758.  
  759.      (When dealing with floating-point comparisons, it is often useful not to
  760.      check for equality, but rather the difference being below a certain
  761.      epsilon factor, 0.01 in this case)
  762.  
  763.      Run "make test" and all should be well.
  764.  
  765.      WWWWHHHHAAAATTTT HHHHAAAASSSS HHHHAAAAPPPPPPPPEEEENNNNEEEEDDDD HHHHEEEERRRREEEE????
  766.  
  767.      Unlike previous examples, we've now run h2xs on a real include file.
  768.      This has caused some extra goodies to appear in both the .pm and .xs
  769.      files.
  770.  
  771.      +o   In the .xs file, there's now a #include declaration with the full
  772.          path to the mylib.h header file.
  773.  
  774.      +o   There's now some new C code that's been added to the .xs file.  The
  775.          purpose of the constant routine is to make the values that are
  776.          #define'd in the header file available to the Perl script (in this
  777.          case, by calling &main::TESTVAL).  There's also some XS code to allow
  778.          calls to the constant routine.
  779.  
  780.      +o   The .pm file has exported the name TESTVAL in the @EXPORT array.
  781.          This could lead to name clashes.  A good rule of thumb is that if the
  782.          #define is going to be used by only the C routines themselves, and
  783.          not by the user, they should be removed from the @EXPORT array.
  784.          Alternately, if you don't mind using the "fully qualified name" of a
  785.          variable, you could remove most or all of the items in the @EXPORT
  786.  
  787.  
  788.  
  789.                                                                        PPPPaaaaggggeeee 11112222
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  797.  
  798.  
  799.  
  800.          array.
  801.  
  802.      +o   If our include file contained #include directives, these would not be
  803.          processed at all by h2xs.  There is no good solution to this right
  804.          now.
  805.  
  806.      We've also told Perl about the library that we built in the mylib
  807.      subdirectory.  That required the addition of only the MYEXTLIB variable
  808.      to the WriteMakefile call and the replacement of the postamble subroutine
  809.      to cd into the subdirectory and run make.  The Makefile.PL for the
  810.      library is a bit more complicated, but not excessively so.  Again we
  811.      replaced the postamble subroutine to insert our own code.  This code
  812.      specified simply that the library to be created here was a static archive
  813.      (as opposed to a dynamically loadable library) and provided the commands
  814.      to build it.
  815.  
  816.      SSSSPPPPEEEECCCCIIIIFFFFYYYYIIIINNNNGGGG AAAARRRRGGGGUUUUMMMMEEEENNNNTTTTSSSS TTTTOOOO XXXXSSSSUUUUBBBBPPPPPPPP
  817.  
  818.      With the completion of Example 4, we now have an easy way to simulate
  819.      some real-life libraries whose interfaces may not be the cleanest in the
  820.      world.  We shall now continue with a discussion of the arguments passed
  821.      to the xsubpp compiler.
  822.  
  823.      When you specify arguments in the .xs file, you are really passing three
  824.      pieces of information for each one listed.  The first piece is the order
  825.      of that argument relative to the others (first, second, etc).  The second
  826.      is the type of argument, and consists of the type declaration of the
  827.      argument (e.g., int, char*, etc).  The third piece is the exact way in
  828.      which the argument should be used in the call to the library function
  829.      from this XSUB.  This would mean whether or not to place a "&" before the
  830.      argument or not, meaning the argument expects to be passed the address of
  831.      the specified data type.
  832.  
  833.      There is a difference between the two arguments in this hypothetical
  834.      function:
  835.  
  836.              int
  837.              foo(a,b)
  838.                      char    &a
  839.                      char *  b
  840.  
  841.      The first argument to this function would be treated as a char and
  842.      assigned to the variable a, and its address would be passed into the
  843.      function foo.  The second argument would be treated as a string pointer
  844.      and assigned to the variable b.  The _v_a_l_u_e of b would be passed into the
  845.      function foo.  The actual call to the function foo that xsubpp generates
  846.      would look like this:
  847.  
  848.              foo(&a, b);
  849.  
  850.      Xsubpp will identically parse the following function argument lists:
  851.  
  852.  
  853.  
  854.  
  855.                                                                        PPPPaaaaggggeeee 11113333
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  863.  
  864.  
  865.  
  866.              char    &a
  867.              char&a
  868.              char    & a
  869.  
  870.      However, to help ease understanding, it is suggested that you place a "&"
  871.      next to the variable name and away from the variable type), and place a
  872.      "*" near the variable type, but away from the variable name (as in the
  873.      complete example above).  By doing so, it is easy to understand exactly
  874.      what will be passed to the C function -- it will be whatever is in the
  875.      "last column".
  876.  
  877.      You should take great pains to try to pass the function the type of
  878.      variable it wants, when possible.  It will save you a lot of trouble in
  879.      the long run.
  880.  
  881.      TTTTHHHHEEEE AAAARRRRGGGGUUUUMMMMEEEENNNNTTTT SSSSTTTTAAAACCCCKKKK
  882.  
  883.      If we look at any of the C code generated by any of the examples except
  884.      example 1, you will notice a number of references to _S_T(n), where n is
  885.      usually 0.  The "ST" is actually a macro that points to the n'th argument
  886.      on the argument stack.  _S_T(0) is thus the first argument passed to the
  887.      XSUB, _S_T(1) is the second argument, and so on.
  888.  
  889.      When you list the arguments to the XSUB in the .xs file, that tells
  890.      xsubpp which argument corresponds to which of the argument stack (i.e.,
  891.      the first one listed is the first argument, and so on).  You invite
  892.      disaster if you do not list them in the same order as the function
  893.      expects them.
  894.  
  895.      EEEEXXXXTTTTEEEENNNNDDDDIIIINNNNGGGG YYYYOOOOUUUURRRR EEEEXXXXTTTTEEEENNNNSSSSIIIIOOOONNNN
  896.  
  897.      Sometimes you might want to provide some extra methods or subroutines to
  898.      assist in making the interface between Perl and your extension simpler or
  899.      easier to understand.  These routines should live in the .pm file.
  900.      Whether they are automatically loaded when the extension itself is loaded
  901.      or loaded only when called depends on where in the .pm file the
  902.      subroutine definition is placed.
  903.  
  904.      DDDDOOOOCCCCUUUUMMMMEEEENNNNTTTTIIIINNNNGGGG YYYYOOOOUUUURRRR EEEEXXXXTTTTEEEENNNNSSSSIIIIOOOONNNN
  905.  
  906.      There is absolutely no excuse for not documenting your extension.
  907.      Documentation belongs in the .pm file.  This file will be fed to pod2man,
  908.      and the embedded documentation will be converted to the manpage format,
  909.      then placed in the blib directory.  It will be copied to Perl's man page
  910.      directory when the extension is installed.
  911.  
  912.      You may intersperse documentation and Perl code within the .pm file.  In
  913.      fact, if you want to use method autoloading, you must do this, as the
  914.      comment inside the .pm file explains.
  915.  
  916.  
  917.  
  918.  
  919.  
  920.  
  921.                                                                        PPPPaaaaggggeeee 11114444
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  929.  
  930.  
  931.  
  932.      See the _p_e_r_l_p_o_d manpage for more information about the pod format.
  933.  
  934.      IIIINNNNSSSSTTTTAAAALLLLLLLLIIIINNNNGGGG YYYYOOOOUUUURRRR EEEEXXXXTTTTEEEENNNNSSSSIIIIOOOONNNN
  935.  
  936.      Once your extension is complete and passes all its tests, installing it
  937.      is quite simple: you simply run "make install".  You will either need to
  938.      have write permission into the directories where Perl is installed, or
  939.      ask your system administrator to run the make for you.
  940.  
  941.      SSSSEEEEEEEE AAAALLLLSSSSOOOO
  942.  
  943.      For more information, consult the _p_e_r_l_g_u_t_s manpage, the _p_e_r_l_x_s manpage,
  944.      the _p_e_r_l_m_o_d manpage, and the _p_e_r_l_p_o_d manpage.
  945.  
  946.      AAAAuuuutttthhhhoooorrrr
  947.  
  948.      Jeff Okamoto <_o_k_a_m_o_t_o@_c_o_r_p._h_p._c_o_m>
  949.  
  950.      Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig,
  951.      and Tim Bunce.
  952.  
  953.      LLLLaaaasssstttt CCCChhhhaaaannnnggggeeeedddd
  954.  
  955.      1996/7/10
  956.  
  957.  
  958.  
  959.  
  960.  
  961.  
  962.  
  963.  
  964.  
  965.  
  966.  
  967.  
  968.  
  969.  
  970.  
  971.  
  972.  
  973.  
  974.  
  975.  
  976.  
  977.  
  978.  
  979.  
  980.  
  981.  
  982.  
  983.  
  984.  
  985.  
  986.  
  987.                                                                        PPPPaaaaggggeeee 11115555
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))                                                      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  995.  
  996.  
  997.  
  998.  
  999.  
  1000.  
  1001.  
  1002.  
  1003.  
  1004.  
  1005.  
  1006.  
  1007.  
  1008.  
  1009.  
  1010.  
  1011.  
  1012.  
  1013.  
  1014.  
  1015.  
  1016.  
  1017.  
  1018.  
  1019.  
  1020.  
  1021.  
  1022.  
  1023.  
  1024.  
  1025.  
  1026.  
  1027.  
  1028.  
  1029.  
  1030.  
  1031.  
  1032.  
  1033.  
  1034.  
  1035.  
  1036.  
  1037.  
  1038.  
  1039.  
  1040.  
  1041.  
  1042.  
  1043.  
  1044.  
  1045.  
  1046.  
  1047.  
  1048.  
  1049.  
  1050.                                                                        PPPPaaaaggggeeee 11116666
  1051.  
  1052.  
  1053.  
  1054.  
  1055.  
  1056.  
  1057.